package com.ruoyi.srmcontract.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.easyExcel.EasyExcelListenerFactory;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.srmcontract.domain.JacContractItem;
import com.ruoyi.srmcontract.domain.JacContractItemImp;
import com.ruoyi.srmcontract.domain.JacContractPriceList;
import com.ruoyi.srmcontract.service.IJacContractItemService;
import com.ruoyi.srmcontract.service.impl.JacContractItemServiceImpl;
import com.ruoyi.srmcontract.utils.MyUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.fasterxml.jackson.annotation.JsonView;


/**
 * 合同物料明细 提供者
 * 
 * @author ygx
 * @date 2020-08-06
 */
@RestController
@RequestMapping("item")
public class JacContractItemController extends MyUtils
{
	private static final Logger log = LoggerFactory.getLogger(JacContractItemServiceImpl.class);
	
	@Autowired
	private IJacContractItemService jacContractItemService;

	
	/**
	 * 查询${tableComment}
	 */
	@GetMapping("get/{companycode}")
	public JacContractItem get(@PathVariable("companycode") String companycode)
	{
		return jacContractItemService.selectJacContractItemById(companycode);
		
	}
	
	/**
	 * 查询合同物料明细列表
	 */
	@GetMapping("list")
	@JsonView(value=JacContractItem.itemListView.class)
	public R list(JacContractItem jacContractItem)
	{
		startPage();
        return result(jacContractItemService.selectJacContractItemList(jacContractItem));
	}
	
	
	/**
	 * 新增保存合同物料明细
	 */
	@PostMapping("save")
	public R addSave(@RequestBody JacContractItem jacContractItem)
	{		
		return toAjax(jacContractItemService.insertJacContractItem(jacContractItem));
	}
	
	
	/**
	 * 批量新增保存合同物料明细
	 */
	@PostMapping("saves")
	public Map<String,String> addSaves(@RequestBody Map<String,List<JacContractItem>> datas)
	{			
		return jacResultMsg(jacContractItemService.insertJacContractItems(datas));
	}

	/**
	 * 批量修改保存合同物料明细
	 */
	@PostMapping("updates")
	public Map<String,String> editSaves(@RequestBody Map<String,Object> datas)
	{	
		return jacResultMsg(jacContractItemService.updateJacContractItems(datas));
	}
	
	/**
	 * 修改保存合同物料明细
	 */
	@PostMapping("update")
	public R editSave(@RequestBody JacContractItem jacContractItem)
	{		
		return toAjax(jacContractItemService.updateJacContractItem(jacContractItem));
	}
	
	
	/**
	 * 删除
	 */
	@PostMapping("remove")
	public Map<String,String> remove(String ids)
	{	
		return jacResultMsg(jacContractItemService.deleteJacContractItemByIds(ids));
	}
	
	/**
	 * 导入excel
	 * @param jacContractItem
	 * @param file
	 * @return
	 * @throws IOException
	 */
    @SuppressWarnings("rawtypes")
	@PostMapping("/imp")
    @ResponseBody
    public Map<String,String>  imp(JacContractItemImp jacContractItemImp,MultipartFile file) throws IOException 
    {   
    	System.out.println(file.getInputStream());
    	Map<String,String> r = new HashMap<String,String>();
    	StringBuffer result = new StringBuffer(); 
    	//行数计数
    	int rowid = 1;
    	List<JacContractItemImp> list = new ArrayList<>();//此list用来存储导入文件中的每行数据
        EasyExcelListenerFactory<JacContractItemImp> tf = new EasyExcelListenerFactory<>(list);
        AnalysisEventListener listener = tf.getListener();
        EasyExcel.read(file.getInputStream(),JacContractItemImp.class,listener).sheet().doRead();//执行完此句后list内就存了文件中数据
        
        if (list.size() == 0)
        {
        	result.append("导入的excel内容无法解析，请确认excel不为空并更换浏览器重新导入！");
        }
        
        for (JacContractItemImp t:list){
        	t.setCompanycode(jacContractItemImp.getCompanycode());
        	t.setContractcode(jacContractItemImp.getContractcode());
        	String excelInsertItem = jacContractItemService.excelInsertItem(t,rowid);//实际导入过程，可以根据自身情况进行相应导入成功失败判断，并返回给前台
    		if (!"1".equals(excelInsertItem))
    		{
    			result.append(excelInsertItem + ";" + "\n");
    		}
    		rowid++;
        }
        
        if ( result != null && StringUtils.isBlank(result))
        {   
    		r.put("msg", "success");
    		r.put("code", "0");
        	return r;
        }
		r.put("msg", "此次导入存在以下问题： " + result.toString());
		r.put("code", "505");
        return r;
    }
    
    /**
     * 导出excel
     * @param jacContractItem
     * @param response
     * @throws IOException
     */
    @GetMapping("/exp")
    @ResponseBody
    public void exp(JacContractItem jacContractItem, HttpServletResponse response) throws IOException {
    	response.setHeader("code","0");
    	try {
			String datetime = new SimpleDateFormat("yyyymmddHHmmss").format(new Date());
			String filename = jacContractItem.getContractcode() + "合同物料明细" + datetime + ".xlsx";
			List<JacContractItem> list = jacContractItemService.selectExcelList(jacContractItem); //被导出数据本身，这里的list只是测试，具体业务可能要进行筛选
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
			EasyExcel.write(response.getOutputStream(), JacContractItem.class).sheet("模板1").doWrite(list);//‘模板1’可根据业务内容自行变更
		} catch (Exception e) {
			response.setHeader("code","500");
			log.error("下载失败",e);
		}
    }
    
    /**
     * 导出模板
     * @param response
     * @param request
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public void importTemplate(HttpServletResponse response, HttpServletRequest request)
    {  
    	response.setHeader("code","0");
        try {
        	String datetime = new SimpleDateFormat("yymmdd").format(new Date());
            String filename = "合同物料明细导入模板" + datetime + ".xlsx";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
            ExcelUtil<JacContractItem> util = new ExcelUtil<>(JacContractItem.class);
            util.importTemplateExcel("用户",response.getOutputStream());
        } catch (Exception e) {
        	response.setHeader("code","500");
            log.error("下载文件失败", e);
        }
    }
	
    /**
     * 查询价格趋势表
     * @param jacContractPriceList
     * @return
     */
    @GetMapping("getContractPrice")
    public R gettContractPrice(JacContractPriceList jacContractPriceList)
    {   
    	startPage();
    	return result(jacContractItemService.selectContractPriceList(jacContractPriceList));
    }

    /**
     * 导出模板
     * @param response
     * @param request
     */
    @GetMapping("importContractPrice")
    @ResponseBody
    public void importContractPrice(JacContractPriceList jacContractPriceList,HttpServletResponse response, HttpServletRequest request)
    {  
    	response.setHeader("code","0");
        try {
        	WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置背景颜色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            //设置头字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short)10);
            headWriteFont.setBold(true);
            headWriteCellStyle.setWriteFont(headWriteFont);
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置内容字体
            WriteFont CellWriteFont = new WriteFont();
            CellWriteFont.setFontHeightInPoints((short)10);
            contentWriteCellStyle.setWriteFont(CellWriteFont);
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        	
            String datetime = new SimpleDateFormat("yyyymmddHHmmss").format(new Date());
			String filename = "合同物料价格明细" + datetime + ".xlsx";
			List<JacContractPriceList> list = jacContractItemService.selectContractPriceList(jacContractPriceList); //被导出数据本身，这里的list只是测试，具体业务可能要进行筛选
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
			EasyExcel.write(response.getOutputStream(), JacContractPriceList.class).head(JacContractPriceList.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板1").doWrite(list);//‘模板1’可根据业务内容自行变更
		} catch (Exception e) {
			response.setHeader("code","500");
			log.error("下载失败",e);
        }
    }
    
}
